package com.lsj.filter;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class LoginFilter extends UsernamePasswordAuthenticationFilter {
    private boolean postOnly = true;
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }
        //检查是否为json格式的请求数据，如果不是，则采用父类方法
        if(request.getContentType().equals(MediaType.APPLICATION_JSON) || request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8)){
            ObjectMapper om = new ObjectMapper();
            Map<String,String> params = new HashMap();;
            try {
                params = om.readValue(request.getInputStream(),Map.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
             String username = params.get("username");
             String password = params.get("password");
             UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
            // Allow subclasses to set the "details" property
            setDetails(request, authRequest);
             return super.getAuthenticationManager().authenticate(authRequest);
        }else{
            return super.attemptAuthentication(request,response);
        }

    }
}
